package name.ekr.edu.threads.chatserver.server;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Reactor {
	private static Logger logger = LoggerFactory.getLogger(Reactor.class);
	private volatile boolean isStopped = false;
	private Acceptor acceptor = null;
	private ConnectionHandler handler = null; 

	
	public Reactor(Acceptor acceptor, ConnectionHandler handler) {
		this.acceptor = acceptor;
		this.handler = handler;
	}

	
	public void start() {
		logger.info("Core started");
		eventLoop();
		logger.info("Core stopped");
	}

	private void eventLoop() {
		while(!isStopped) {
			new AsyncHandlerCall(acceptor.accept()).start();
		}
	}
	
	private class AsyncHandlerCall extends Thread {
		private Connection connection;
		
		public AsyncHandlerCall(Connection connection) {
			this.connection = connection;
		}

		@Override
		public void run() {
			handler.handle(connection);
		}
	}
}
